import {
  Decoration,
  ViewPlugin,
  MatchDecorator,
  EditorView,
  WidgetType,
} from "@codemirror/view";

class AttributeWidget extends WidgetType {
  constructor(name) {
    super();
    this.name = name;
  }

  eq(other) {
    return this.name == other.name;
  }

  toDOM() {
    let element = document.createElement("span");
    element.style.cssText = `
      line-height: 20px;
      padding: 0 4px;
      margin: 0 1.5px;
      background: lightblue;
      font-size: 14px;
      color: #5f748e;
      background-color: rgba(95, 116, 142, .1);
      border-radius: 2px;
    `;
    element.textContent = this.name;
    return element;
  }

  ignoreEvent() {
    return false;
  }
}

const attributeMatcher = new MatchDecorator({
  regexp: /\[(.+?)\]/g,
  decoration: (match) => {
    return Decoration.replace({
      widget: new AttributeWidget(match[1]),
    })
  }
});

export const attributePlugin = ViewPlugin.fromClass(
  class {
    attributes;

    constructor(view) {
      this.attributes = attributeMatcher.createDeco(view);
    }

    update(update) {
      this.attributes = attributeMatcher.updateDeco(
        update,
        this.attributes
      );
    }
  },
  {
    decorations: (instance) => instance.attributes,
    provide: (plugin) =>
      EditorView.atomicRanges.of((view) => {
        return view.plugin(plugin)?.attributes || Decoration.none;
      }),
  }
);
